// api.ts
const baseURL = 'https://learning.cpolar.cn/'
//测试环境
// const baseURL = 'http://134.98.98.224:8889/'
// const baseURL = 'http://localhost:8889/'



function getUrl(url: string) {
    return baseURL + url.replace(/\/api/, 'api')

    // return baseURL + url.replace(/\/api/g, '')
}

export function postRestful(url: string, data: object, hideLoading: boolean, method: 'POST' | 'PUT' = 'POST') {
    if (!hideLoading) {
        uni.showLoading({
            title: "Loading...",
        });
    }

    return new Promise((resolve, reject) => {
        uni.request({
            url: getUrl(url),
            method: method,
            data: data,
            success: (res) => {
                uni.hideLoading();
                if (res && res.data) resolve(res.data);
                else reject(res);

            },
            fail: (err) => {
                uni.hideLoading();
                uni.showToast({
                    title: "保存失败, "+err,
                    icon: 'none'
                })
                reject(err);

            }
        });
    });
}

export function getRestful(url: string, hideLoading: boolean) {
    if (!hideLoading) {
        uni.showLoading({
            title: "Loading...",
        });
    }

    return new Promise((resolve, reject) => {
        uni.request({
            url: getUrl(url),
            method: 'GET',
            success: (res) => {
                uni.hideLoading();
                if (res && res.data) resolve(res.data);
                else resolve(true)
            },
            fail: (err) => {
                uni.hideLoading();
                reject(err);
            }
        });
    });
}

export function delRestful(url: string, hideLoading: boolean) {
    if (!hideLoading) {
        uni.showLoading({
            title: "Loading...",
        });
    }

    return new Promise((resolve, reject) => {
        uni.request({
            url: getUrl(url),
            method: 'DELETE',
            success: (res) => {
                uni.hideLoading();
                if (res && res.data) resolve(res.data);
                else resolve(true)
            },
            fail: (err) => {
                uni.hideLoading();
                reject(err);
            }
        });
    });
}
